/*
 * Created on Mar 25, 2010
 */
package ro.letsdoitromania;

import ro.letsdoitromania.forms.LoginForm;
import com.mgmaps.app.PendingForm;
import com.mgmaps.net.Downloadable;
import com.mgmaps.tools.StringTools;
import com.mgmaps.utils.ExtLogger;
import com.mgmaps.utils.LS;

public class AuthSaltRequest implements Downloadable {

  public String getURL() {
    return LDIRSettings.AUTH_URL + "/" + LDIRSettings.username;
  }

  public void notifyDownloaded(byte[][] data) {
    try {
      if (PendingForm.getInstance().isCancelled())
        ExtLogger.error("Login cancelled");
      else {
        final String response = StringTools.byteArrayToString(data[0]);
        
        ExtLogger.debug("AUTHSERVICE RESPONSE: " + response);
        
        final String salt = StringTools.extractXMLContent(response, "string");
        if (salt != null && salt.length() > 0)
          LDIRSettings.usersalt = salt;
        else
          throw new Exception("No such user");
      
        // continue with the trash point request
        LDIRSettings.dl.enqueue(new TrashPointRequest());
      }
    }
    catch (Exception ex) {
      notifyError("Invalid username or password -- " + ex.getMessage());
    }
  }

  public void notifyError(String message) {
    ExtLogger.error("ERROR: " + message);
    LDIRSettings.usersalt = "";
    LoginForm.getInstance().show(LS.get("ldir.login.error"));
  }

}
